package hero_info

import (
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
)

func (s *Hero_info_service) S2C_RecombinCell(conn ziface.IConnection, roleid int64, msg *pb.RecombinCellC2S) pb.ErrorCodeManager {
	cells, code := s.onRecombinCell(roleid, msg.Cellserids)
	msgS2C := &pb.UpdateCellListS2C{}
	msgS2C.Cells = make([]*pb.HeroCellData, 0)
	for _, cv := range cells {
		msgS2C.Cells = append(msgS2C.Cells, cv.To_PbData())
	}
	defer func() {
		if msgS2C != nil {
			zlog.Debugf("ProtocolManager_RecombinCell %v", msgS2C)
			defer func() {
				conn.SendBuffPBMsg(uint32(pb.ProtocolManager_RecombinCell), msgS2C)
			}()
		}
	}()
	return code
}

func (s *Hero_info_service) onRecombinCell(roleid int64, cellserids []int32) (map[int32]*Cache_hero_info_field_cell, pb.ErrorCodeManager) {
	hero := Hero_info_serviceObj.LoadByRoleId(roleid)
	maxRecombineCellCount := Hero_info_serviceObj.GetRecombinCellCount() //N细胞重组成一个
	if hero != nil && cellserids != nil && len(cellserids) >= maxRecombineCellCount {
		isAllSameLvCell := true //是否是相同等级的细胞
		tmpLv := int32(0)       //当前融合的细胞等级
		csidcnt := len(cellserids)
		for i := 0; i < csidcnt; i++ {
			if cv, ok := hero.RoleCells[cellserids[i]]; ok {
				if tmpLv == 0 {
					tmpLv = cv.Lv
				} else {
					isAllSameLvCell = isAllSameLvCell && (cv.Lv == tmpLv)
				}
			}
		}
		if isAllSameLvCell && tmpLv > 0 {
			if currecombincells, cc1, _, _ := Hero_info_serviceObj.GetNextLevelRecombinCells(tmpLv); cc1 {
				usecells := make(map[int32]int32)

				for i := 0; i < maxRecombineCellCount; i++ {
					tsid := cellserids[i]
					if _, ok := usecells[tsid]; !ok {
						usecells[tsid] = 0
					}
					usecells[tsid]++
				}

				isEnough := hero.CheckEnoughCell(usecells) //是否有足够的细胞
				if tarcellcfgid, k1 := util.GetRandWeight(currecombincells); isEnough && k1 {
					acv := make(map[int32]int32)
					acv[tarcellcfgid] = 1

					rstCells := make(map[int32]*Cache_hero_info_field_cell, 0)

					if addcells, a1 := hero.AddRoleCell(acv); a1 {
						for sid, cv := range addcells {
							rstCells[sid] = cv
						}
					}

					if removecells, a1 := hero.RemoveRoleCell(usecells); a1 {
						for sid, cv := range removecells {
							rstCells[sid] = cv
						}
					}

					defer hero.SaveDB_HeroInfo_Cells()

					return rstCells, pb.ErrorCodeManager_SUCCESS
				} else {
					return nil, pb.ErrorCodeManager_HERO_INFO_ERRORRULE_RECOMBINCELL
				}
			}
		} else {
			return nil, pb.ErrorCodeManager_HERO_INFO_ERRORRULE_RECOMBINCELL
		}
	} else {
		return nil, pb.ErrorCodeManager_HERO_INFO_ERRORRULE_RECOMBINCELL
	}
	return nil, pb.ErrorCodeManager_SUCCESS
}
